package ink.lovejinhu.swardToOffer;

import ink.lovejinhu.common.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;

/**
 * @author jinhu
 * created 2021-08-12 9:12
 */
public class Offer_032_I {
    /**
     * 层序遍历
     *
     * @param root
     * @return
     */
    public int[] levelOrder(TreeNode root) {
        if (root == null) {
            return new int[0];
        }
        LinkedList<TreeNode> treeNodes = new LinkedList<>();
        ArrayList<TreeNode> res = new ArrayList<>();
        treeNodes.add(root);
        while (!treeNodes.isEmpty()) {
            TreeNode poll = treeNodes.poll();
            if (poll.left != null) {
                treeNodes.add(poll.left);
            }
            if (poll.right != null) {
                treeNodes.add(poll.right);
            }
            res.add(poll);
        }
        int[] ints = new int[res.size()];
        for (int i = 0; i < res.size(); i++) {
            ints[i] = res.get(i).val;

        }
        return ints;
    }
}
